package com.weilive.pay.gate;

import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.weilive.core.netty.http.HttpServlet;
import com.weilive.core.utils.QueryStringDecoder;
import com.weilive.pay.msg.ToPayMsg;
import com.weilive.pay.service.weix.WxPayService;

/**
 * 获取支付结果
 * 
 * @author houzhiwei
 *
 */
@Service
public class QueryPayResultServlet extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(QueryPayResultServlet.class);
	@Autowired
	private WxPayService wxPayService;

	private static final int QUERY_TYPE_WEIX = 1;// 微信

	@Override
	public String getServletPath() {
		return "/pay/query";
	}

	@Override
	public HttpResponse processRequest(HttpRequest request) throws Exception {
		// post
		QueryStringDecoder decoder = decodeQueryString(request);

		int query_type = decoder.getInt("query_type", 0);// 查询类型
		String out_trade_no = decoder.get("out_trade_no", "");// 订单号
		// String trade_no = decoder.get("trade_no", "");// 流水号
		// 处理支付结果
		// 获取支付宝POST过来反馈信息
		try {

			if (query_type == QUERY_TYPE_WEIX) {
				String toMsg = wxPayService.query(out_trade_no);
				logger.info("用户请求支付数据结果,out_trade_no=" + out_trade_no + ",result=" + toMsg);
				return createJsonResponse(toMsg);
			} else {
				String toMsg = new ToPayMsg("0", "查询类型错误", null, null).toString();
				logger.info("用户请求支付数据结果,out_trade_no=" + out_trade_no + ",result=" + toMsg);
				return createJsonResponse(toMsg);
			}

		} catch (Exception e) {
			e.printStackTrace();
			String toMsg = new ToPayMsg("0", "内部错误", null, null).toString();
			logger.info("用户请求支付数据结果,out_trade_no=" + out_trade_no + ",result=" + toMsg);
			return createJsonResponse(toMsg);
		}

	}
}